package com.jd.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.jd.basic.exception.BusinessException;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.BaiduAIUtils;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.domain.ShopAuditLog;
import com.jd.org.dto.shopDto;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopAuditLogMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.org.service.IShopService;
import com.jd.user.domain.Logininfo;
import com.jd.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
// 查询的方法比较多，使用查询的事务配置
// 只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    @Transactional
    public void settlement(Shop shop) { // 店铺入驻
        // 空值校验 店铺参数
        if (StrUtil.isBlank(shop.getName()) || StrUtil.isBlank(shop.getTel()) ||
                StrUtil.isBlank(shop.getAddress())) {
            throw new BusinessException("店铺信息不能为空！");
        }
        // 名字智能审核
        if (!BaiduAIUtils.TextCensor(shop.getName())) {
            throw new BusinessException("名称违规！");
        }
        // log审核
        if (shop.getLogo() != null) {
            if (!BaiduAIUtils.ImgCensor(shop.getLogo())) {
                throw new BusinessException("logo图标违规！");
            }
        }
        // 空值校验 管理员参数
        if (StrUtil.isBlank(shop.getAdmin().getUsername()) || StrUtil.isBlank(shop.getAdmin().getPassword()) ||
                StrUtil.isBlank(shop.getAdmin().getPhone()) || StrUtil.isBlank(shop.getAdmin().getEmail())
                || StrUtil.isBlank(shop.getAdmin().getComfirmPassword())) {
            throw new BusinessException("管理员信息不能为空！");
        }
        // 入驻过的店铺不能再次入驻，通过三个参数校验
        Shop dbShop = shopMapper.findBySettle(shop);
        if (dbShop != null) {
            throw new BusinessException("该店铺已入驻，请登录！如果忘记密码，请联系管理员！");
        }
        // 操作数据库
        shopMapper.add(shop); // 根据页面数据添加店铺 id要自增长处理，xml
        Employee admin = shop.getAdmin(); // 获取admin信息
        admin.setShopId(shop.getId()); // 设置shopId
        String salt = RandomUtil.randomString(32); // 设置盐值
        String md5Pwd = SecureUtil.md5(admin.getPassword() + salt);// 对密码加密加盐
        admin.setSalt(salt); // 设置盐值
        admin.setPassword(md5Pwd); // 设置加密后的密码
        // 维护logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(admin,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(false);
        logininfoMapper.add(logininfo);
        admin.setLogininfoId(logininfo.getId());
        employeeMapper.add(admin); // 添加进数据库 id自增长处理
        shop.setAdminId(admin.getId()); // 设置shop管理员id
        shopMapper.update(shop); // 修改shop
    }

    @Override
    @Transactional
    public void auditPass(ShopAuditLog shopAuditLog) { // 店铺审批通过
        // 改变店铺状态从待审核改为待激活
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shop.setState(2);
        shopMapper.update(shop); // 修改状态
        // 店铺审批日志管理
        shopAuditLog.setState(1); // 设置为审批成功
        shopAuditLog.setAuditId(shop.getAdminId()); // 设置操作管理员
        shopAuditLogMapper.add(shopAuditLog); // 添加审批日志
        // 发送激活邮件
        Employee employee = employeeMapper.findOne(shop.getAdminId());
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("1178050280@qq.com"); // 发件人
            helper.setSubject("店铺激活邮件");
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText("<h1>你的店铺已经审批成功!!!</h1><img src='"+shop.getLogo()+"' >" +
                    "<a href='http://localhost:8080/shop/active/"+shopAuditLog.getShopId()+"'>点击该链接激活</a>", true);
            //添加附件
//            helper.addAttachment("p7.jpg", new File("C:\\Users\\Administrator\\Pictures\\photos\\p7.jpg"));
//            helper.addAttachment("g1.gif", new File("C:\\Users\\Administrator\\Pictures\\g1.gif"));
            //收件人
            helper.setTo(employee.getEmail());
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    @Transactional
    public void auditReject(ShopAuditLog shopAuditLog) { // 店铺审批失败
        // 改变店铺状态从待审核改为驳回
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shop.setState(4);
        shopMapper.update(shop); // 修改状态
        // 店铺审批日志管理
        shopAuditLog.setState(0); // 设置为审批失败
        shopAuditLog.setAuditId(shop.getAdminId()); // 设置操作管理员
        shopAuditLogMapper.add(shopAuditLog); // 添加审批日志
        // 发送入驻失败邮件
        Employee employee = employeeMapper.findOne(shop.getAdminId());
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("1178050280@qq.com"); // 发件人
            helper.setSubject("店铺入驻失败！");
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText("<h1>你的店铺入驻失败!!!</h1>" +
                    "<a href='http://localhost:8081/#/register'>点击该链接重新入驻！</a>", true);
            //添加附件
//            helper.addAttachment("p7.jpg", new File("C:\\Users\\Administrator\\Pictures\\photos\\p7.jpg"));
//            helper.addAttachment("g1.gif", new File("C:\\Users\\Administrator\\Pictures\\g1.gif"));
            //收件人
            helper.setTo(employee.getEmail());
            javaMailSender.send(mimeMessage);
            shopMapper.del(shopAuditLog.getShopId()); // 删除数据库店铺信息
//            employeeMapper.del(shop.getAdminId()); // 删除数据库管理员信息
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional
    public List<shopDto> columnEcharts() {
        return shopMapper.columnEcharts();
    }
}
